import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  Popconfirm,
  Space,
  InputNumber,
} from "antd";
import { connect } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useState, useRef } from "react";
import { PlusOutlined } from "@ant-design/icons";

const Page = (props) => {
  const { dispatch, submitLoading, allCourse } = props;
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const actionRef = useRef();

  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
    });
  }, []);

  const editInfo = (params) => {
    setOpen(true);
    dispatch({
      type: `${namespace}/queryItemInfo`,
      params,
      callback: (res) => {
        actionRef.current?.reload();
        form.setFieldsValue({ ...res });
        setOpen(true);
      },
    });
  };

  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: (res) => {
        actionRef.current?.reload();
      },
    });
  };

  const operate = {
    title: "操作",
    dataIndex: "operate",
    align: "center",
    fixed: "right",
    hideInSearch: true,
    render: (_, record) => {
      const { courseStatus } = record;
      const _courseStatus = parseInt(courseStatus, 10);
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          {_courseStatus == 0 ? (
            <Popconfirm
              title="禁用后该分类讲不再能使用,是否确定禁用?"
              onConfirm={() => toggleState({ id: record.id, courseStatus: 1 })}
            >
              <Button type="link" danger>
                禁用
              </Button>
            </Popconfirm>
          ) : (
            <Button
              type="link"
              onClick={() => toggleState({ id: record.id, courseStatus: 0 })}
            >
              启用
            </Button>
          )}
        </Space>
      );
    },
  };

  const submitForm = async () => {
    const res = await form.validateFields();
    if (res) {
      dispatch({
        type: `${namespace}/submitItem`,
        params: {
          ...res,
          categoryOrder: res.categoryOrder ? res.categoryOrder : 0,
        },
        callback: () => {
          setOpen(false);
          form.resetFields();
          actionRef.current?.reload();
        },
      });
    }
  };

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        // scroll={{ x: 1500 }}
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            key="add"
            onClick={() => {
              form.resetFields();
              setOpen(true);
            }}
          >
            新增分类
          </Button>,
        ]}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumns({ operate, allCourse })}
      />

      <Modal
        open={open}
        title={form.getFieldValue("id") ? "编辑" : "新增"}
        forceRender
        width="50%"
        onCancel={() => {
          setOpen(!open);
          form.resetFields();
        }}
        footer={
          <Space>
            <Button
              onClick={() => {
                form.resetFields();
                setOpen(false);
              }}
            >
              取消
            </Button>
            <Button onClick={submitForm} loading={submitLoading} type="primary">
              确定
            </Button>
          </Space>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ categoryOrder: "0" }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label="分类名称"
            name="categoryName"
            rules={[
              { required: true, message: "分类名称不能为空,长度不超过30个字" },
            ]}
          >
            <Input placeholder="请输入" maxLength={30} showCount />
          </Form.Item>
          <Form.Item label="排序值" name="categoryOrder">
            <InputNumber
              min={0}
              max={10000}
              placeholder="请输入排序值,数值越大越靠前"
              controls={false}
              style={{ width: "100%" }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
